# -*- coding: utf-8 -*-


import os
import json
import matplotlib.pyplot as plt
import numpy as np
from scipy.interpolate import make_interp_spline
from liner_analysis import analyze

from matplotlib import font_manager  # 导入字体管理模块

my_font = font_manager.FontProperties(fname="C:/WINDOWS/Fonts/STSONG.TTF")

root_path = "E:\\毕设数据"

x_tick = ['2000', '2001', '2002', '2003', '2004', '2005', '2006', '2007', '2008', '2009', '2010', '2011', '2012',
          '2013', '2014', '2015', '2016', '2017', '2018', '2019', '2020']

font = {'family': 'serif',
        'color': 'black',
        'weight': 'normal',
        'size': 16,
        }

tick_font = {'family': "STSONG",
             # 'color': 'black',
             'weight': 'normal',
             'size': 12,
             }

with open('./avgRecord.json') as f:
    data = json.load(f)


def data_keys_I():
    """数据一级键， 分类标准"""
    dirs = os.listdir(root_path)
    keys_I = []
    for i in dirs:
        if i.endswith("Excel"):
            keys_I.append(i)
    return keys_I


def data_keys_II(key_I):
    """数据二级键，分类标准下的各类别"""
    path_I = os.path.join(root_path, key_I)
    key_II = os.listdir(path_I)
    return key_II


def get_data(key) -> (dict, int):
    key1 = data_keys_I()
    if key in key1 and key != "WuhanNDVI_Excel":
        return data[key], 1
    else:
        if key == "WuhanNDVI_Excel":
            return data[key], 2
        for i in key1:
            key2 = data_keys_II(i)
            if key in key2:
                return data[i][key], 2
        return "not such data"


def calc_new_xy(old_x, old_growth_y, old_year_y) -> tuple:
    xx = [x for x in range(0, len(old_x), 1)]
    xn = np.array(xx)
    x_smooth = np.linspace(xn.min(initial=None), xn.max(initial=None), 300)
    y_year_avg_smooth = make_interp_spline(xn, old_year_y)(x_smooth)
    y_growth_avg_smooth = make_interp_spline(xn, old_growth_y)(x_smooth)
    return x_smooth, y_year_avg_smooth, y_growth_avg_smooth


def draw_picture(fig, key):
    data = get_data(key)[0]
    data_flag = get_data(key)[1]
    if data_flag == 2:
        x = x_tick
        y_growth = data.get("growth_avg")
        y_year = data.get("year_avg")
        new = calc_new_xy(x, y_growth, y_year)
        new_x = new[0]
        new_y_year = new[1]
        new_y_growth = new[2]
        xx = np.arange(0, len(x), 1)
        y_predict_year_avg = analyze(data, "year_avg")[0] + xx * analyze(data, "year_avg")[1]
        y_predict_growth_avg = analyze(data, "growth_avg")[0] + xx * analyze(data, "year_avg")[1]

        plt__ = fig.add_subplot(111)
        plt__.plot(new_x, new_y_year, label="年平均变化趋势")
        plt__.plot(new_x, new_y_growth, label="生长期（4-10月）变化趋势")
        plt__.plot(x, y_predict_year_avg, label="预测年平均变化趋势 \ny_year = %fx + %f"
                                                % (analyze(data, "year_avg")[1], analyze(data, "year_avg")[0]),
                                                linestyle = "--")
        plt__.plot(x, y_predict_growth_avg, label="预测生长期（4-10月）变化趋势 \ny_growth = %fx + %f"
                                                  % (analyze(data, "growth_avg")[1], analyze(data, "growth_avg")[0]),
                                                linestyle="--")
        if key == "WuhanNDVI_Excel":
            title = "武汉市"
        else:
            title = key
        plt__.set_title("%sNDVI变化趋势图" % title, fontproperties=my_font, fontsize=20, pad=20)
        plt__.set_xlabel("Year", fontdict=font)
        plt__.set_ylabel("NDVI", fontdict=font)
        plt.xticks([i for i in range(0, len(x), 1)], x_tick, fontproperties='Times New Roman', size=10)
        plt.yticks(fontproperties='Times New Roman', size=10)
        plt.grid(alpha=0.3, color='g')
        plt.legend(prop=tick_font)
        plt.savefig("E:\\毕设数据\\pictures\\" + "%sNDVI变化趋势图.pdf" % title)


if __name__ == '__main__':
    key1 = data_keys_I()
    key2 = data_keys_II(key1[0])

    print(key1)
    for i in key1:
        if i == "WuhanNDVI_Excel":
            print(i)
            print(get_data(i))
            fig = plt.figure(figsize=(15, 10))
            draw_picture(fig, i)
        # else:
        #     fig = plt.figure(figsize=(20, 10))
        #     draw_picture(fig, i)
        #     break
